from flask import Flask,request,g,render_template
from flask_cors import CORS
from src.service import API_CONFIG_V1
from src.utils.db import connect,MYSQL_CONFIG
from src.utils.index import colored_text
import json


app = Flask(__name__)
app.register_blueprint(API_CONFIG_V1,url_prefix="/api")

CORS(app)

@app.route("/index")
def index():
    return render_template("index.html",goodList=[{'img':'xxx','name':'第一个商品'},{'img':'yyy','name':'第二个商品'}])
@app.route("/")
def login():
    return render_template("login.html")

# flask钩子函数 每次发起请求前触发
@app.before_request
def before_request():
    # 若请求前数据库没有连接，需要连接上数据库
    if not hasattr(g,'db'):
        setattr(g,'db',connect(MYSQL_CONFIG.HOST,
                               MYSQL_CONFIG.PORT,
                               MYSQL_CONFIG.USERNAME,
                               MYSQL_CONFIG.PASSWORD,
                               MYSQL_CONFIG.DATABASE))
    # 若当前请求头里包含用户id，带入到全局变量g上
    userId = request.headers.get('Userid')
    if userId is not None:
        setattr(g,'userId',userId)

# flask钩子函数 每次请求完成后触发
@app.after_request
def after_request(response):
    # 释放数据库
    if hasattr(g,'db') and g.db is not None:
        g.db.close()
        delattr(g,'db')
        print(colored_text("---------数据库释放成功---------","green"))
    if hasattr(g,'userId'):
        delattr(g,'userId')
    try:
        if not response.data:
            print(json.loads(response.data))
    except:
        pass   
    return response


if __name__ == "__main__":
    app.run(host="0.0.0.0",port=8848,debug=True)